/**
 * Created by chenyong on 2015/11/9.
 * 基于jQuery的BigPixel.Base基础插件
 */

var BrowserDetect={
    init:function()
    {
        this.browser=this.searchString(this.dataBrowser)||"An unknown browser";
        this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"an unknown version";
        this.OS=this.searchString(this.dataOS)||"an unknown OS";
        this.isMobile=this.isMobileDevice(this.MobileDevices)||false;
    },
    searchString:function(data){
        for(var i=0;i<data.length;i++)
        {
            var dataString=data[i].string;var dataProp=data[i].prop;
            this.versionSearchString=data[i].versionSearch||data[i].identity;
            if(dataString)
            {
                if(dataString.indexOf(data[i].subString)!=-1)return data[i].identity;
            }
            else if(dataProp)return data[i].identity;}
    },
    isMobileDevice:function(data){
        for(var i=0;i<data.length;i++)
        {
            var dataString=data[i].string;
            var dataProp=data[i].prop;
            this.versionSearchString=data[i].versionSearch||data[i].identity;
            if(dataString)
            {
                if(dataString.indexOf(data[i].subString)!=-1)return true;
            }
            else if(dataProp)return false;
        }
    },
    searchVersion:function(dataString){var index=dataString.indexOf(this.versionSearchString);if(index==-1)return;return parseFloat(dataString.substring(index+this.versionSearchString.length+1));},
    dataBrowser:[
        {string:navigator.userAgent,subString:"Chrome",identity:"Chrome"},
        {string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},
        {string:navigator.vendor,subString:"Apple",identity:"Safari",versionSearch:"Version"},
        {prop:window.opera,identity:"Opera",versionSearch:"Version"},
        {string:navigator.vendor,subString:"iCab",identity:"iCab"},
        {string:navigator.vendor,subString:"KDE",identity:"Konqueror"},
        {string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},
        {string:navigator.vendor,subString:"Camino",identity:"Camino"},
        {string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},
        {string:navigator.userAgent,subString:"MSIE",identity:"Explorer",versionSearch:"MSIE"},
        {string:navigator.userAgent,subString:"Trident",identity:"Explorer",versionSearch:"rv"},
        {string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},
        {string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}
    ],
    MobileDevices:[
        {string:navigator.userAgent,subString:"iPhone",identity:"iPhone"},
        {string:navigator.userAgent,subString:"Android",identity:"Android"}

    ],
    dataOS:[
        {string:navigator.platform,subString:"Win",identity:"Windows"},
        {string:navigator.platform,subString:"Mac",identity:"Mac"},
        {string:navigator.userAgent,subString:"iPhone",identity:"iPhone/iPod"},
        {string:navigator.platform,subString:"Linux",identity:"Linux"}
    ]
};
BrowserDetect.init();

jQuery.support.cors = true;
(function ($) {

    //缓存工厂
    $.createCache = function( requestFunction ) {
        var cache = {};
        return function( key, callback ) {
            if ( !cache[ key ] ) {
                cache[ key ] = $.Deferred(function( defer ) {
                    requestFunction( defer, key );
                }).promise();
            }
            return cache[ key ].done( callback );
        };
    };

    //加载js文件
    $.cachedGetScript = $.createCache(function(defer,url){
        //$.getScript( url ).then( defer.resolve, defer.reject );
        $.ajax({
            url:url,
            dataType:"script",
            cache:true,
            success:defer.resolve,
            error:defer.reject
        });
    });

    //获取Url参数
    $.getUrlParam = function (name){
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r !== null) return unescape(r[2]); return null;
    };

    //增加或更新Url参数值
    $.updateUrlParams = function(url, name, value){
        var r = url;
        if (r !== null && r != 'undefined' && r !== "") {
            value = encodeURIComponent(value);
            var reg = new RegExp("(^|)" + name + "=([^&]*)(|$)");
            var tmp = name + "=" + value;
            if (url.match(reg) !== null) {
                r = url.replace(eval(reg), tmp);
            }
            else {
                if (url.match("[\?]")) {
                    r = url + "&" + tmp;
                } else {
                    r = url + "?" + tmp;
                }
            }
        }
        return r;
    };

    //设置Cookie
    $.setCookie = function(name,value,expire)
    {
        var exp = new Date();
        exp.setTime(exp.getTime() + expire*60*1000);
        var _domain = window.location.hostname;
        document.cookie = name + "="+ decodeURI (value) + ";expires=" + exp.toGMTString() + ";domain="+_domain + ";path=/";
    };
    //读取Cookie
    $.getCookie = function(name)
    {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg))
            return decodeURI(arr[2]);
        else
            return null;
    };

    //删除Cookie
    $.removeCookie = function(name)
    {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval=getCookie(name);
        if(cval!==null)
            document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    };



    var settings = {
        'debug': false,
        'timeout': 120
    };

    $.currentUser = {};

    var _getCurrentUserInfo = function(callback){
        $.ajax({
            type: "GET",
            url: "/auth/me",
            beforeSend: function(request) {
                request.setRequestHeader("authorization", "Bearer " + $.getCookie("token"));
            },
            success: function(userinfo){
                callback(null,userinfo);
            },
            error: function(err)
            {
                callback(err);
            }
        });
    };

    //当前用户

    if ($.getCookie("token")) {
        _getCurrentUserInfo(function(err,data){
            if(!err)
            {
                $.currentUser = data;
                var args  = Array.prototype.slice.call(arguments);
                if(typeof(  $.bigpixel.OnUserinfoReadyFunc) == "function" ){
                    $.bigpixel.OnUserinfoReadyFunc.apply(null,args);
                }
            }
        });
    }

    var methods = {
        debug: function () {
            return settings.debug;
        },

        AjaxGetJson:function(url,data,callback)
        {
            if (arguments.length === 2 && typeof data === 'function') {
                callback = data;
                data = null;
            }

            $.ajax({
                type: "GET",
                timeout:3000,
                url: url,

                beforeSend: function(request) {
                    if($.getCookie("token"))
                    {
                        request.setRequestHeader("authorization", "Bearer " + $.getCookie("token"));
                    }
                },
                success: function(d){
                    callback(null,d);
                },
                error: function(e)
                {
                    callback(e);
                }
            });

        },
        AjaxPostData:function(url,data,callback)
        {
            if (arguments.length === 2 && typeof data === 'function') {
                callback = data;
                data = null;
            }
            $.ajax({
                type: "POST",
                timeout:3000,
                url: url,
                data:data,
                beforeSend: function(request) {
                    if($.getCookie("token"))
                    {
                        request.setRequestHeader("authorization", "Bearer " + $.getCookie("token"));
                    }
                },
                success: function(d){
                    callback(null,d);
                },
                error: function(e)
                {
                    callback(e);
                }
            });
        },

        AjaxPutData:function(url,data,callback)
        {
            if (arguments.length === 2 && typeof data === 'function') {
                callback = data;
                data = null;
            }
            $.ajax({
                type: "PUT",
                timeout:3000,
                url: url,
                data:data,
                beforeSend: function(request) {
                    if($.getCookie("token"))
                    {
                        request.setRequestHeader("authorization", "Bearer " + $.getCookie("token"));
                    }
                },
                success: function(d){
                    callback(null,d);
                },
                error: function(e)
                {
                    callback(e);
                }
            });
        },

        //判断Url是否有效
        IsValidUrl:function(url,callback)
        {
            $.ajax({
                url: url,
                type: 'HEAD',
                timeout:1500,
                complete: function(response) {
                    $.ajaxSetup({timeout:3000});
                    if(response.status == 200) {
                        callback(true);
                    } else {
                        callback(false);
                    }
                }
            });
        },
        getCurrentUser:function(callback)
        {
            if($.currentUser.hasOwnProperty('_id'))
            {
                callback(currentUser);
            }
            else if (!$.getCookie("token"))
            {
                callback(null);
            }
            else
            {
                this.AjaxGetJson("/auth/me",function(err,data){
                  if(!err)
                  {
                      $.currentUser = data;
                      var args  = Array.prototype.slice.call(arguments);
                      if(typeof(  $.bigpixel.OnUserinfoReadyFunc) == "function" ){
                          $.bigpixel.OnUserinfoReadyFunc.apply(null,args);
                      }
                      callback($.currentUser);
                  }
                    else
                  {
                      callback(null);
                  }
                });
            }
        },
        //登录
        login:function(){
            var _currUrl = window.location.href;
            var krpano = document.getElementById("panoSWFObject");
            if(krpano !== null)
            {
                var fov = Number( krpano.get("view.fov") );
                var v = Number( krpano.get("view.vlookat") );
                var h   = Number( krpano.get("view.hlookat") );
                h = h%360; // restrict to +-360
                if (h<=-180){
                    h = 360+h;
                }
                else if(h>180){
                    h = 360-h;
                }
                //pos = {'fov':fov,'ath':h,'atv':v};

                _currUrl = $.updateUrlParams(_currUrl,'ath',h);
                _currUrl = $.updateUrlParams(_currUrl,'atv',v);
                _currUrl = $.updateUrlParams(_currUrl,'fov',fov);
            }
            $.setCookie("reutrnurl",_currUrl,30);

            //微信登陆

            window.location.href = '/auth/wechat?returnurl=' + _currUrl;

        },
        //注销
        logout:function(){
            $.removeCookie("token");
            $.currentUser = {};
        },
        isLoggedIn: function() {
            return $.currentUser.hasOwnProperty('_id');
        },
        //检测是否登录
        isLoggedInAsync:function(callback){
            if($.currentUser.hasOwnProperty('_id'))
            {
                callback($.currentUser.hasOwnProperty('_id'));
            }
            else if (!$.getCookie("token"))
            {
                callback(false);
            }
            else
            {
                this.AjaxGetJson("/auth/me",function(err,data){
                    if(!err)
                    {
                        $.currentUser = data;
                        var args  = Array.prototype.slice.call(arguments);
                        if(typeof(  $.bigpixel.OnUserinfoReadyFunc) == "function" ){
                            $.bigpixel.OnUserinfoReadyFunc.apply(null,args);
                        }
                    }
                    callback($.currentUser.hasOwnProperty('_id'));
                });
            }
        },
        OnUserinfoReady:function(func)
        {
            $.bigpixel.OnUserinfoReadyFunc = func;
        },
        //初始化微信分享
        initWechat:function(){
            var ua = navigator.userAgent.toLowerCase();
            if(ua.match(/MicroMessenger/i)=="micromessenger") {
                $.cachedGetScript('http://res.wx.qq.com/open/js/jweixin-1.0.0.js',function(){
                    if(typeof(socialinfo) == "object")
                    {
                        $.getJSON('http://srv.bigpixel.cn/api/weixin/getsignature?url=' + encodeURIComponent(socialinfo.link)).done(function (data) {

                            wx.config({debug: false, appId: data.appId, timestamp: data.timestamp, nonceStr: data.nonceStr, signature: data.signature, jsApiList: ['onMenuShareTimeline', 'onMenuShareQQ', 'onMenuShareAppMessage', 'onMenuShareWeibo']});
                            wx.ready(function () {
                                wx.onMenuShareTimeline(socialinfo);
                                wx.onMenuShareAppMessage(socialinfo);
                                wx.onMenuShareQQ(socialinfo);
                                wx.onMenuShareWeibo(socialinfo);
                            });
                        });
                    }
                });
            }
        },
        //重置微信分享链接
        resetWechatShareInfo:function(shareinfo)
        {
            wx.ready(function () {
                wx.onMenuShareTimeline(shareinfo);
                wx.onMenuShareAppMessage(shareinfo);
                wx.onMenuShareQQ(shareinfo);
                wx.onMenuShareWeibo(shareinfo);
            });

        }
    };

    $.bigpixel = methods;

}(jQuery));

